#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <taskLib.h>

int iTimerTaskId;

void timer_handler(timer_t timerId, int arg)
{
	STATUS task_status;
	int iDelayTick;
	BOOL isReady, isSuspended, isPended, isDelayed;
	task_status = taskIdVerify(iTimerTaskId);
	isReady = taskIsReady(iTimerTaskId);
	isSuspended = taskIsSuspended(iTimerTaskId);
	isPended = taskIsPended(iTimerTaskId);
	isDelayed = taskIsDelayed(iTimerTaskId, &iDelayTick);
	printf("timer %p expired tid = %08X, timer task status = %d\n", timerId, taskIdSelf(), task_status);
	printf("timer task status: READY[%d] SUSPENDED[%d] PENDED[%d] DELAYED[%d]\n", isReady, isSuspended, isPended, isDelayed);
}
void timer_handler2(timer_t timerId, int arg)
{
	STATUS task_status;
	int iDelayTick;
	BOOL isReady, isSuspended, isPended, isDelayed;
	task_status = taskIdVerify(iTimerTaskId);
	isReady = taskIsReady(iTimerTaskId);
	isSuspended = taskIsSuspended(iTimerTaskId);
	isPended = taskIsPended(iTimerTaskId);
	isDelayed = taskIsDelayed(iTimerTaskId, &iDelayTick);
	printf("timer2 %p expired tid = %08X, timer task status = %d\n", timerId, taskIdSelf(), task_status);
	printf("timer task status: READY[%d] SUSPENDED[%d] PENDED[%d] DELAYED[%d]\n", isReady, isSuspended, isPended, isDelayed);
}


int init_timer()
{
	int iRetval;
	timer_t timer1Id, timer2Id;
	/*struct sigevent event;*/
	struct itimerspec timer_spec;
	/*
	event.sigev_notify = SIGEV_TASK_SIGNAL;
	event.sigev_signo = SIGRTMIN;
	event.sigev_value.sival_int = 1234;
*/
	/*iRetval = timer_create(CLOCK_REALTIME, &event, &timerId);*/
	
	iRetval = timer_create(CLOCK_REALTIME, NULL, &timer1Id);
	iRetval = timer_create(CLOCK_REALTIME, NULL, &timer2Id);
	if (iRetval == ERROR)
	{
		printf("timer create failed\n");
		return -1;
	}
	iRetval = timer_connect(timer1Id, timer_handler, 4567);
	iRetval = timer_connect(timer2Id, timer_handler2, 789);
	if (iRetval == ERROR)
	{
		printf("timer connect failed\n");
		return -1;
	}
	timer_spec.it_value.tv_sec = 2;
	timer_spec.it_value.tv_nsec = 0;
	timer_spec.it_interval.tv_sec = 0;
	timer_spec.it_interval.tv_nsec = 500 * 1000 * 1000;
	iRetval = timer_settime(timer1Id, 0, &timer_spec, NULL);
	if (iRetval == ERROR)
	{
		printf("set timer failed\n");
		return -1;
	}
	timer_spec.it_value.tv_sec = 2;
	timer_spec.it_value.tv_nsec = 0;
	timer_spec.it_interval.tv_sec = 0;
	timer_spec.it_interval.tv_nsec = 300 * 1000 * 1000;
	iRetval = timer_settime(timer2Id, 0, &timer_spec, NULL);
	if (iRetval == ERROR)
	{
		printf("set timer failed\n");
		return -1;
	}
	return 0;
}

void timer_task()
{
	
	printf("timer task tid = %X\n", taskIdSelf());
	init_timer();
	while (1)
	{
		taskDelay(60);
	}
}
int testmain(int a, int b, int c)
{
	printf("a=%d b=%d c=%d\n",a,b,c);
	printf("testmain tid = %X\n", taskIdSelf());
	iTimerTaskId = taskSpawn("Timer task", 210, 0, 4096, (FUNCPTR)timer_task, 0,0,0,0,0,0,0,0,0,0);
/*
	while (1)
	{
		taskDelay(60);
	}
	*/
	return 0;
}
